package cn.edu.zjicm.wordsnet_d.activity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.activity.base.WordBaseActivity;
import cn.edu.zjicm.wordsnet_d.adapter.common.ArrayListAdapter;
import cn.edu.zjicm.wordsnet_d.data.MobclickAgentData;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.datapersistent.FileManager;
import cn.edu.zjicm.wordsnet_d.download.JudgeNetwork;
import cn.edu.zjicm.wordsnet_d.download.UpdateManager;
import cn.edu.zjicm.wordsnet_d.lock.LockService;
import cn.edu.zjicm.wordsnet_d.synchronize.UserInterface;
import cn.edu.zjicm.wordsnet_d.util.DateTimeUtils;
import cn.edu.zjicm.wordsnet_d.util.NightModeUtil;
import cn.edu.zjicm.wordsnet_d.util.Utils;
import cn.edu.zjicm.wordsnet_d.view.BadgeView;

import com.umeng.analytics.MobclickAgent;
import com.umeng.fb.FeedbackAgent;
import com.umeng.fb.SyncListener;
import com.umeng.fb.model.Conversation;
import com.umeng.fb.model.Reply;

public class SettingActivity extends WordBaseActivity implements OnItemClickListener {
	public static void startActivity(Context context) {
		Intent i = new Intent(context, SettingActivity.class);
		context.startActivity(i);
	}

	private final int LIST_TOP = 0;
	private final int SETTING_INDEX_SYNC = 1;
	private final int SETTING_INDEX_CONSOLIDATE_MODE = 2;
	private final int SETTING_INDEX_DOWNLOAD_VOICE = 3;
	private final int SETTING_INDEX_AUTO_PRONUNCIATION = 4;
	private final int SETTING_INDEX_DIVIDOR0 = 5;
	private final int SETTING_INDEX_STDUY_NOTIFICATION = 6;
	private final int SETTING_INDEX_STDUY_NOTIFICATION_VOICE = 7;
	private final int SETTING_INDEX_DIVIDOR1 = 8;
	private final int SETTING_INDEX_LOCK_SCREEN = 9;
	private final int SETTING_INDEX_LOCK_SCREEN_NUM = 10;
	private final int SETTING_INDEX_LOCK_SCREEN_WALLPAPER = 11;
	private final int SETTING_INDEX_DIVIDOR2 = 12;
	private final int SETTING_INDEX_HELP_CENTER = 13;
	private final int SETTING_INDEX_FEEDBACK = 14;
	private final int SETTING_INDEX_APP_RECOMMEND = 15;
	private final int SETTING_INDEX_DIVIDOR3 = 16;
	private final int SETTING_INDEX_CHECK_UPDATE = 17;
	private final int SETTING_INDEX_ABOUT_US = 18;
	private final int LIST_BOTTOM = 19;

	private final int CHOOSE_RING_CALLBACK = 111;
	private MediaPlayer mMediaPlayer;

	private ListView mList;
	private View mMask; // 弹出下载窗口时的遮罩

	private boolean addRedPoint = false;

	// 只有点击“锁屏复习单词个数”，“意见反馈”才刷新列表
	private boolean shouldRefresh = false;

	// notification出现的flag
	public static boolean notifyFlag = false;
	/*
	 * private Notification notification; private NotificationManager nManager;
	 */
	private UpdateManager uManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitleBarStyle(TITLE_BAR_STYLE_BACK_BUTTON);
		setTitleText("设置");
		setContentView(R.layout.activity_setting);
		UpdateManager.getCurVersion(this);
		mMask = findViewById(R.id.popupwindow_mask);
		mList = (ListView) findViewById(R.id.setting_list);
		mList.setAdapter(mAdapter);
		mList.setOnItemClickListener(this);

		mAdapter.add(LIST_TOP, "");
		mAdapter.add(SETTING_INDEX_SYNC, "同步");
		mAdapter.add(SETTING_INDEX_CONSOLIDATE_MODE, "修改熟词巩固模式");
		mAdapter.add(SETTING_INDEX_DOWNLOAD_VOICE, "下载语音包");
		mAdapter.add(SETTING_INDEX_AUTO_PRONUNCIATION, "学习过程中自动发音");
		mAdapter.add(SETTING_INDEX_DIVIDOR0, "");
		mAdapter.add(SETTING_INDEX_STDUY_NOTIFICATION, "学习提醒");
		mAdapter.add(SETTING_INDEX_STDUY_NOTIFICATION_VOICE, "提醒铃声");
		mAdapter.add(SETTING_INDEX_DIVIDOR1, "");
		mAdapter.add(SETTING_INDEX_LOCK_SCREEN, "锁屏复习单词");
		mAdapter.add(SETTING_INDEX_LOCK_SCREEN_NUM, "锁屏复习单词个数");
		mAdapter.add(SETTING_INDEX_LOCK_SCREEN_WALLPAPER, "锁屏壁纸更换");
		// 如果注释掉设置界面的夜间模式开关，将BaseActivity中onResume方法中的夜间模式检测注释掉。
		// mAdapter.add(SETTING_INDEX_NIGHT_MODE, "夜间模式");
		mAdapter.add(SETTING_INDEX_DIVIDOR2, "");
		mAdapter.add(SETTING_INDEX_HELP_CENTER, "帮助中心");
		mAdapter.add(SETTING_INDEX_FEEDBACK, "意见反馈");
		mAdapter.add(SETTING_INDEX_APP_RECOMMEND, "应用推荐");
		mAdapter.add(SETTING_INDEX_DIVIDOR3, "");
		mAdapter.add(SETTING_INDEX_CHECK_UPDATE, "检查更新");
		mAdapter.add(SETTING_INDEX_ABOUT_US, "关于");
		mAdapter.add(LIST_BOTTOM, "");
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
		if (shouldRefresh) {
			notifyData();
		}
		checkFeedback();
	}

	private void checkFeedback() {
		if (!AppPreference.isHasFeedback(this)) {
			Conversation conversation = new FeedbackAgent(this).getDefaultConversation();
			conversation.sync(new SyncListener() {

				@Override
				public void onSendUserReply(List<Reply> arg0) {
				}

				@Override
				public void onReceiveDevReply(List<Reply> arg0) {
					if (arg0 != null && arg0.size() > 0) {
						AppPreference.setHasFeedback(SettingActivity.this, true);
						addRedPoint = true;
						mAdapter.notifyDataSetChanged();
					} else {
						addRedPoint = false;
						mAdapter.notifyDataSetChanged();
					}
				}
			});
		} else {
			addRedPoint = true;
			mAdapter.notifyDataSetChanged();
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (null != mMediaPlayer) {
			mMediaPlayer.release();
		}
	}

	ArrayListAdapter<String> mAdapter = new ArrayListAdapter<String>() {
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = getLayoutInflater().inflate(R.layout.view_setting_item, null);
			RelativeLayout ll = (RelativeLayout) view.findViewById(R.id.view_setting_item_linearlayour);
			TextView divide = (TextView) view.findViewById(R.id.setting_divide);
			if (NightModeUtil.isNightModeNow())
				divide.setVisibility(View.GONE);
			else
				divide.setVisibility(View.VISIBLE);

			TextView tv = (TextView) view.findViewById(R.id.view_setting_item_textview);
			tv.setText(getItem(position));
			if (position == LIST_TOP) {
				view.setVisibility(View.INVISIBLE);
			} else if (position == SETTING_INDEX_SYNC) {
				Utils.setListItemTop(ll);

				long time = AppPreference.getSyncTime(SettingActivity.this);
				int vc = AppPreference.getSyncVC(SettingActivity.this);
				if (UserInterface.getInstance(SettingActivity.this).isLogin() && vc != 0) {
					TextView tv1 = (TextView) view.findViewById(R.id.view_setting_item_textview1);
					tv1.setVisibility(View.VISIBLE);
					tv1.setText("上一次同步时间:" + DateTimeUtils.getTimeStr(time));
				}
			}
			// ---------------------------------------------------------
			else if (position == SETTING_INDEX_CONSOLIDATE_MODE) {
				TextView tv1 = (TextView) view.findViewById(R.id.view_setting_item_textview1);
				tv1.setVisibility(View.VISIBLE);
				int num = AppPreference.getConsolidateMode(SettingActivity.this);
				if (0 == num) {
					tv1.setText("选择题模式");
				} else if (1 == num) {
					tv1.setText("经典认记模式");
				} else {
					tv1.setVisibility(View.GONE);
				}
			} else if (position == SETTING_INDEX_AUTO_PRONUNCIATION) {
				Utils.setListItemBottom(ll, divide);
				ImageView iv = (ImageView) view.findViewById(R.id.iv);
				iv.setVisibility(View.GONE);
				final TextView tb = (TextView) view.findViewById(R.id.tb);
				tb.setVisibility(View.VISIBLE);
				if (AppPreference.isAutoPronunciation(SettingActivity.this))
					tb.setBackgroundResource(R.drawable.study_notification_on);
				else
					tb.setBackgroundResource(R.drawable.study_notification_off);

				OnClickListener clickListenre = new OnClickListener() {
					@Override
					public void onClick(View v) {
						if (AppPreference.isAutoPronunciation(SettingActivity.this)) {
							AppPreference.setAutoPronunciation(SettingActivity.this, false);
							tb.setBackgroundResource(R.drawable.study_notification_off);
							Toast.makeText(SettingActivity.this, "关闭自动发音", Toast.LENGTH_SHORT).show();
						} else {
							AppPreference.setAutoPronunciation(SettingActivity.this, true);
							Toast.makeText(SettingActivity.this, "开启自动发音", Toast.LENGTH_SHORT).show();
							tb.setBackgroundResource(R.drawable.study_notification_on);
						}
					}
				};
				ll.setOnClickListener(clickListenre);
				tb.setOnClickListener(clickListenre);
			} else if (position == SETTING_INDEX_STDUY_NOTIFICATION) {
				Utils.setListItemTop(ll);
				ImageView iv = (ImageView) view.findViewById(R.id.iv);
				iv.setVisibility(View.GONE);
				final TextView tb = (TextView) view.findViewById(R.id.tb);
				tb.setVisibility(View.VISIBLE);
				if (AppPreference.isStudyNotification(SettingActivity.this))
					tb.setBackgroundResource(R.drawable.study_notification_on);
				else
					tb.setBackgroundResource(R.drawable.study_notification_off);

				OnClickListener clickListenre = new OnClickListener() {
					@Override
					public void onClick(View v) {
						if (AppPreference.isStudyNotification(SettingActivity.this)) {
							AppPreference.setStudyNotification(SettingActivity.this, false);
							tb.setBackgroundResource(R.drawable.study_notification_off);
							Toast.makeText(SettingActivity.this, "关闭学习提醒", Toast.LENGTH_SHORT).show();
						} else {
							AppPreference.setStudyNotification(SettingActivity.this, true);
							Toast.makeText(SettingActivity.this, "开启学习提醒", Toast.LENGTH_SHORT).show();
							tb.setBackgroundResource(R.drawable.study_notification_on);
						}
					}
				};
				ll.setOnClickListener(clickListenre);
				tb.setOnClickListener(clickListenre);
			} else if (position == SETTING_INDEX_DOWNLOAD_VOICE) {
				// ImageView iv = (ImageView) view.findViewById(R.id.iv);
				// iv.setVisibility(View.GONE);
			} else if (position == SETTING_INDEX_STDUY_NOTIFICATION_VOICE) {
				Utils.setListItemBottom(ll, divide);
				TextView tv1 = (TextView) view.findViewById(R.id.view_setting_item_textview1);
				tv1.setVisibility(View.VISIBLE);
				tv1.setText(getCurrentNotificationRingName());
			}
			// ---------------------------------------------------------
			else if (position == SETTING_INDEX_LOCK_SCREEN) {
				Utils.setListItemTop(ll);

				ImageView iv = (ImageView) view.findViewById(R.id.iv);
				iv.setVisibility(View.GONE);
				final TextView tb = (TextView) view.findViewById(R.id.tb);
				tb.setVisibility(View.VISIBLE);
				if (AppPreference.isLockScreen(SettingActivity.this))
					tb.setBackgroundResource(R.drawable.study_notification_on);
				else
					tb.setBackgroundResource(R.drawable.study_notification_off);
				OnClickListener listener = new OnClickListener() {
					@Override
					public void onClick(View v) {
						// 关闭锁屏复习单词
						if (AppPreference.isLockScreen(SettingActivity.this)) {
							AppPreference.setLockScreen(SettingActivity.this, false);
							LockService.unDisableLock(SettingActivity.this); // 解除锁屏屏蔽
							tb.setBackgroundResource(R.drawable.study_notification_off);
							Toast.makeText(SettingActivity.this, "关闭锁屏复习", Toast.LENGTH_SHORT).show();
							MobclickAgentData.enableLockScreen(SettingActivity.this, false);
						} else {// 打开锁屏
							AppPreference.setLockScreen(SettingActivity.this, true);
							LockService.disableLock(SettingActivity.this); // 锁屏屏蔽
							tb.setBackgroundResource(R.drawable.study_notification_on);
							Toast.makeText(SettingActivity.this, "打开锁屏复习", Toast.LENGTH_SHORT).show();
							MobclickAgentData.enableLockScreen(SettingActivity.this, true);
							// 这里先这么写，跳转到引导页
							// startActivity(new
							// Intent(SettingActivity.this,LockScreenGuideActivity.class));
						}
					}
				};
				tb.setOnClickListener(listener);
				ll.setOnClickListener(listener);
			} else if (position == SETTING_INDEX_LOCK_SCREEN_NUM) {
				TextView tv1 = (TextView) view.findViewById(R.id.view_setting_item_textview1);
				tv1.setVisibility(View.VISIBLE);
				int num = AppPreference.getLockScreenWordsNum(SettingActivity.this);
				tv1.setText("复习" + num + "个单词");
			} else if (position == SETTING_INDEX_LOCK_SCREEN_WALLPAPER) {
				Utils.setListItemBottom(ll, divide);
			} else if (position == SETTING_INDEX_HELP_CENTER) {
				Utils.setListItemTop(ll);
			} else if (position == SETTING_INDEX_FEEDBACK) {
				if (addRedPoint) {
					TextView attchLayout = (TextView) view.findViewById(R.id.red_point);
					attchLayout.setVisibility(View.VISIBLE);
					BadgeView badgeView = new BadgeView(SettingActivity.this, attchLayout);
					badgeView.setTextSize(7);
					badgeView.setBadgePosition(BadgeView.POSITION_CENTER);
					badgeView.show();
				}
			} else if (position == SETTING_INDEX_APP_RECOMMEND) {
				Utils.setListItemBottom(ll, divide);
			} else if (position == SETTING_INDEX_CHECK_UPDATE) {
				Utils.setListItemTop(ll);
			} else if (position == SETTING_INDEX_ABOUT_US) {
				TextView tv1 = (TextView) view.findViewById(R.id.view_setting_item_textview1);
				tv1.setVisibility(View.VISIBLE);
				tv1.setText(UpdateManager.curVersionName);
				Utils.setListItemBottom(ll, divide);
			} else if (position == LIST_BOTTOM) {
				view.setVisibility(View.INVISIBLE);
			} else {// 分割框
				LinearLayout llForPadding = (LinearLayout) view.findViewById(R.id.linearlayout_for_padding);
				llForPadding.setPadding(0, 0, 0, 0);
				ImageView iv = (ImageView) view.findViewById(R.id.iv);
				iv.setVisibility(View.GONE);
				if (NightModeUtil.isNightModeNow())
					ll.setBackgroundColor(Color.alpha(0));
				else
					ll.setBackgroundColor(Color.rgb(242, 238, 233));
				divide.setVisibility(View.GONE);
			}

			return ll;
		}
	};

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {

		if (arg0.equals(mList)) {
			if (position == SETTING_INDEX_CONSOLIDATE_MODE) {
				int choosedModeIndex = AppPreference.getConsolidateMode(SettingActivity.this);
				new AlertDialog.Builder(this).setTitle("修改熟词巩固模式")
						.setSingleChoiceItems(new String[] { "选择题模式", "经典认记模式" }, choosedModeIndex == -1 ? 0 : choosedModeIndex, new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								AppPreference.setConsolidateMode(SettingActivity.this, which);
								mAdapter.notifyDataSetChanged();
								dialog.dismiss();
							}
						}).setNegativeButton("取消", null).show();
				shouldRefresh = true;
			} else if (position == SETTING_INDEX_DOWNLOAD_VOICE) {
				DownloadVoicePackActivity.mStartActivity(this, 0);
			} else if (position == SETTING_INDEX_LOCK_SCREEN_NUM) {
				new AlertDialog.Builder(this)
						.setTitle("锁屏复习单词个数")
						.setSingleChoiceItems(new String[] { "复习1个单词", "复习3个单词", "复习5个单词", "复习7个单词", "复习9个单词" }, (AppPreference.getLockScreenWordsNum(SettingActivity.this) - 1) / 2,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog, int which) {
										int lockScreenWordsNum = 0;
										if (which == 0)
											lockScreenWordsNum = 1;
										else if (which == 1)
											lockScreenWordsNum = 3;
										else if (which == 2)
											lockScreenWordsNum = 5;
										else if (which == 3)
											lockScreenWordsNum = 7;
										else if (which == 4)
											lockScreenWordsNum = 9;
										if (lockScreenWordsNum != AppPreference.getLockScreenWordsNum(SettingActivity.this)) {
											AppPreference.setLockScreenWordsNum(SettingActivity.this, lockScreenWordsNum);
											mAdapter.notifyDataSetChanged();
										}
										dialog.dismiss();
									}
								}).setNegativeButton("取消", null).show();

				shouldRefresh = true;
			} else if (position == SETTING_INDEX_STDUY_NOTIFICATION_VOICE) {
				AlertDialog alertDialog = new AlertDialog.Builder(this).setTitle("设置 提醒铃声")
						.setSingleChoiceItems(new String[] { "静音", "默认铃声", "使用系统默认通知铃声", "选取系统铃声" }, getCurrentNotificationIndex(), new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								if (which == 0) {
									AppPreference.setNotificationRing(SettingActivity.this, "null");
									if (null != mMediaPlayer && mMediaPlayer.isPlaying()) {
										mMediaPlayer.pause();
										mMediaPlayer.stop();
									}
								} else if (which == 1) {
									String defaultNotificationRing = "android.resource://" + SettingActivity.this.getPackageName() + "/" + R.raw.notify;
									AppPreference.setNotificationRing(SettingActivity.this, defaultNotificationRing);
									playNorificationRing(Uri.parse(defaultNotificationRing));
								} else if (which == 2) {
									Uri defaultNotificationRing = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
									AppPreference.setNotificationRing(SettingActivity.this, defaultNotificationRing.toString());
									playNorificationRing(defaultNotificationRing);
								} else if (which == 3) {
									Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
									intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION);
									intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, false);
									intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false);
									intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "设置 提醒铃声");
									startActivityForResult(intent, CHOOSE_RING_CALLBACK);
									if (null != mMediaPlayer && mMediaPlayer.isPlaying()) {
										mMediaPlayer.pause();
										mMediaPlayer.stop();
									}
								}
							}
						}).setNegativeButton("确定", null).show();
				alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
					@Override
					public void onDismiss(DialogInterface dialog) {
						if (null != mMediaPlayer && mMediaPlayer.isPlaying()) {
							mMediaPlayer.pause();
							mMediaPlayer.stop();
						}
						notifyData();
					}
				});
				shouldRefresh = true;
			} else if (position == SETTING_INDEX_LOCK_SCREEN_WALLPAPER) {
				LockWallpaperSelectActivity.startActivity(this);
			} else if (position == SETTING_INDEX_HELP_CENTER) {
				HelpCenterActivity.startActivity(this);
			} else if (position == SETTING_INDEX_FEEDBACK) {
				FeedbackAgent agent = new FeedbackAgent(this);
				Intent intent = new Intent();
				intent.setClass(this, FeedBackForUMengActivity.class);
				startActivity(intent);
			} else if (position == SETTING_INDEX_APP_RECOMMEND) {
				if (JudgeNetwork.getInstance(this).isMobileConnected() || JudgeNetwork.getInstance(this).isWifiConnected()) {
					startActivity(new Intent(SettingActivity.this, AppRecommendActivity.class));
				} else {
					Toast.makeText(this, "网络未连接，请检查网络设置", Toast.LENGTH_SHORT).show();
				}

			} else if (position == SETTING_INDEX_CHECK_UPDATE) {
				checkUpdate();
				MobclickAgentData.checkUpdate(this);
			} else if (position == SETTING_INDEX_ABOUT_US) {
				startActivity(new Intent(SettingActivity.this, AboutUsActivity.class));
			} else if (position == SETTING_INDEX_SYNC) {
				if (!UserInterface.getInstance(SettingActivity.this).isLogin()) {
					RegisterActivity.startActivity(SettingActivity.this, RegisterActivity.TO_SETTING);
				} else {
					showSyncConfirmWindow();
				}
			}
		}
	}

	private int getCurrentNotificationIndex() {
		String currentNotificationRing = AppPreference.getNotificationRing(SettingActivity.this);
		String defaultNotificationRing = "android.resource://" + SettingActivity.this.getPackageName() + "/" + R.raw.notify;
		String defaultSystemNotificationRing = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION).toString();
		if ("null".equals(currentNotificationRing)) {
			return 0;
		} else if (defaultNotificationRing.equals(currentNotificationRing)) {
			return 1;
		} else if (defaultSystemNotificationRing.equals(currentNotificationRing)) {
			return 2;
		} else {
			return 3;
		}

	}

	private String getCurrentNotificationRingName() {
		int currentNotificationRingIndex = getCurrentNotificationIndex();
		String currentNotificationRingName = "默认铃声";
		switch (currentNotificationRingIndex) {
		case 0:
			currentNotificationRingName = "静音";
			break;
		case 1:
			currentNotificationRingName = "默认铃声";
			break;
		case 2:
			String stringUri = AppPreference.getNotificationRing(SettingActivity.this);
			if (null == stringUri) {
				currentNotificationRingName = "默认铃声";
			} else
				currentNotificationRingName = "系统通知铃声  " + getNotificationRingName(stringUri);
			break;
		case 3:
			String stringUri2 = AppPreference.getNotificationRing(SettingActivity.this);
			if (null == stringUri2) {
				currentNotificationRingName = "默认铃声";
			} else
				currentNotificationRingName = "自定义铃声  " + getNotificationRingName(stringUri2);
			break;
		}
		return currentNotificationRingName;
	}

	private String getNotificationRingName(String stringUri) {
		if (null == stringUri)
			return null;
		String fileName = null;
		Uri notificationRingNameUri = Uri.parse(stringUri);
		Ringtone r = RingtoneManager.getRingtone(this, notificationRingNameUri);
		fileName = r.getTitle(this);
		return fileName;
	}

	Handler syncHandler = new Handler() {
		ProgressDialog dialog2 = null;

		public void handleMessage(android.os.Message msg) {
			if (msg.what != UserInterface.MSG_START)
				if (dialog2 != null) {
					dialog2.dismiss();
					dialog2 = null;
				}

			switch (msg.what) {
			case UserInterface.MSG_START:
				dialog2 = ProgressDialog.show(SettingActivity.this, null, "同步中...");
				break;
			case UserInterface.MSG_SUCCESS:
				// String data = (String) msg.obj;
				// if (data.length() == 0)
				// data = "上传";
				// else
				// data = "下传:";// + data;
				// Toast.makeText(SettingActivity.this, "同步成功\n" + data,
				// Toast.LENGTH_SHORT).show();
				Toast.makeText(SettingActivity.this, "同步成功", Toast.LENGTH_SHORT).show();
				mAdapter.notifyDataSetChanged();
				break;
			case UserInterface.MSG_UNSUCCESS:
				Toast.makeText(SettingActivity.this, "同步失败", Toast.LENGTH_SHORT).show();
				break;
			case UserInterface.MSG_BAD_NETWORK:
				Toast.makeText(SettingActivity.this, UserInterface.MSG_BAD_NETWORK_STRING, Toast.LENGTH_SHORT).show();
				break;
			case UserInterface.MSG_WEB_SITE_ACCESS_FAILURE:
				Toast.makeText(SettingActivity.this, UserInterface.MSG_WEB_SITE_ACCESS_FAILURE_STRING, Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
		};
	};

	// Handler syncBeforeLogoutHandler = new Handler() {
	// ProgressDialog dialog2 = null;
	//
	// public void handleMessage(android.os.Message msg) {
	// if (msg.what != RegisterAndLogin.MSG_START)
	// if (dialog2 != null) {
	// dialog2.dismiss();
	// dialog2 = null;
	// }
	//
	// switch (msg.what) {
	// case RegisterAndLogin.MSG_START:
	// dialog2 = ProgressDialog.show(SettingActivity.this, null, "同步中...");
	// break;
	// case RegisterAndLogin.MSG_SUCCESS:
	// Toast.makeText(SettingActivity.this, "同步成功", Toast.LENGTH_SHORT).show();
	// logout();
	// break;
	// case RegisterAndLogin.MSG_BAD_NETWORK:
	// Toast.makeText(SettingActivity.this, "请确认网络是否连接",
	// Toast.LENGTH_SHORT).show();
	// break;
	// case RegisterAndLogin.MSG_UNSUCCESS:
	// Toast.makeText(SettingActivity.this, "同步失败", Toast.LENGTH_SHORT).show();
	// break;
	// case RegisterAndLogin.MSG_WEB_SITE_ACCESS_FAILURE:
	// Toast.makeText(SettingActivity.this, "无法访问网站，请确认网络是否连接",
	// Toast.LENGTH_SHORT).show();
	// break;
	// default:
	// break;
	// }
	// };
	// };

	void sync() {
		syncHandler.sendMessage(syncHandler.obtainMessage(UserInterface.MSG_START));
		UserInterface.getInstance(SettingActivity.this).sync(syncHandler);
	}

	// void syncBeforeLogout() {
	// syncBeforeLogoutHandler.sendMessage(syncBeforeLogoutHandler.obtainMessage(RegisterAndLogin.MSG_START));
	// RegisterAndLogin.getInstance(SettingActivity.this).sync(syncBeforeLogoutHandler);
	// }

	private PopupWindow mSyncConfirmWindow;

	void showSyncConfirmWindow() {
		if (AppPreference.isShowSyncHint(this)) {
			sync();
			return;
		}

		View view = View.inflate(this, R.layout.window_check_sync, null);
		if (mSyncConfirmWindow == null) {
			// init PopWindow cotentview
			TextView confirmButton = (TextView) view.findViewById(R.id.sync_confirm_button);
			final CheckBox showHintCheckBox = (CheckBox) view.findViewById(R.id.sync_showhint_checkbox);
			confirmButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mSyncConfirmWindow.dismiss();
					mSyncConfirmWindow = null;

					sync();

					AppPreference.setShowSyncHint(SettingActivity.this, showHintCheckBox.isChecked());
				}
			});
			mSyncConfirmWindow = new PopupWindow(view, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
			mSyncConfirmWindow.setFocusable(true);
			mSyncConfirmWindow.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.transparent_bg_drawable));
			mSyncConfirmWindow.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss() {
					mMask.setVisibility(View.GONE);
				}
			});
		}
		mMask.setVisibility(View.VISIBLE);
		mSyncConfirmWindow.showAtLocation(mMask, Gravity.CENTER, 0, 0);
	}

	void checkUpdate() {
		// new CheckUpdateThread().start();
		uManager = new UpdateManager(this, UpdateManager.curVersionCode);
		uManager.checkUpdateInfo();
	}

	void share() {
		Intent intent = new Intent(Intent.ACTION_SEND);

		intent.setType("image/*");
		Uri uri = Uri.fromFile(new File(FileManager.DOWNLOAD_PATH + "logo96.png"));
		// Uri uri = Uri.fromFile(new File("file:///android_asset/logo96.png"));
		// Uri uri = Uri.parse("file:///android_asset/logo96.png");
		// Uri uri =
		// Uri.parse("android.resource://cn.edu.zjicm.wordsnet_d/"+R.raw.logo96);
		// Uri uri = Uri.parse("android.resource://" + this.getPackageName() +
		// "/" + R.raw.notify);
		intent.putExtra(Intent.EXTRA_STREAM, uri);

		// intent.setType("text/plain");
		// intent.setPackage("com.sina.weibo");
		intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
		intent.putExtra(Intent.EXTRA_TEXT, "分享优趣背单词 http://openbox.mobilem.360.cn/d.php?p=cn.edu.zjicm.wordsnet_d");
		intent.putExtra(Intent.EXTRA_TITLE, "分享优趣背单词");
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(Intent.createChooser(intent, "分享到"));
	}

	void share1() {
		Intent it = new Intent(Intent.ACTION_SEND);
		it.setType("text/plain");
		List<ResolveInfo> resInfo = getPackageManager().queryIntentActivities(it, 0);
		if (!resInfo.isEmpty()) {
			List<Intent> targetedShareIntents = new ArrayList<Intent>();
			for (ResolveInfo info : resInfo) {
				Intent targeted = new Intent(Intent.ACTION_SEND);
				targeted.setType("text/plain");
				ActivityInfo activityInfo = info.activityInfo;

				// judgments : activityInfo.packageName, activityInfo.name, etc.
				if (activityInfo.packageName.contains("bluetooth") || activityInfo.name.contains("bluetooth")) {
					continue;
				}
				if (activityInfo.packageName.contains("gm") || activityInfo.name.contains("mail")) {
					targeted.putExtra(Intent.EXTRA_SUBJECT, "分享");
					targeted.putExtra(Intent.EXTRA_TEXT, "你好 ");
					targeted.putExtra(Intent.EXTRA_TITLE, "分享优趣背单词");
				} else if (activityInfo.packageName.contains("zxing")) {
					targeted.putExtra(Intent.EXTRA_SUBJECT, "分享");
					targeted.putExtra(Intent.EXTRA_TEXT, "你好 ");
					targeted.putExtra(Intent.EXTRA_TITLE, "分享优趣背单词");
				} else {
					targeted.putExtra(Intent.EXTRA_SUBJECT, "分享");
					targeted.putExtra(Intent.EXTRA_TEXT, "你好 ");
					targeted.putExtra(Intent.EXTRA_TITLE, "分享优趣背单词");
				}
				targeted.setPackage(activityInfo.packageName);
				targetedShareIntents.add(targeted);
			}

			Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), "分享到");

			if (chooserIntent == null) {
				return;
			}

			// A Parcelable[] of Intent or LabeledIntent objects as set with
			// putExtra(String, Parcelable[]) of additional activities to place
			// a the front of the list of choices, when shown to the user with a
			// ACTION_CHOOSER.
			chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[] {}));

			try {
				startActivity(chooserIntent);
			} catch (android.content.ActivityNotFoundException ex) {
				Toast.makeText(this, "Can't find share component to share", Toast.LENGTH_SHORT).show();
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != RESULT_OK) {
			return;
		} else if (requestCode == CHOOSE_RING_CALLBACK) {
			Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
			AppPreference.setNotificationRing(SettingActivity.this, uri.toString());
		}
	}

	private void notifyData() {
		mAdapter.notifyDataSetChanged();
		shouldRefresh = false;
	}

	private void playNorificationRing(Uri uri) {
		if (mMediaPlayer == null)
			mMediaPlayer = new MediaPlayer();
		else if (mMediaPlayer.isPlaying()) {
			mMediaPlayer.pause();
			mMediaPlayer.stop();
		}
		try {
			mMediaPlayer.reset();
			mMediaPlayer.setDataSource(SettingActivity.this, uri);
			mMediaPlayer.prepare();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		mMediaPlayer.start();
	}

}
